package com.llmcu.source.javase.thread.daemon;

import java.util.concurrent.TimeUnit;

/**
 * 测试普通线程会不会伴随主线程结束而结束：默认不会，除非设置为守护线程
 *
 * @author liuling
 * @date 2024/11/12 19:59
 */
public class DaemonThreadLife {
    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(()->{
            System.out.println(Thread.currentThread().getName()+"start...");
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+"end...");
        });

        thread.setName("threadXyz");
        // 默认是非守护线程，主线程消亡后，该线程依旧运行；
        // 设置为true变为守护线程后，会跟随主线程一起消亡
        thread.setDaemon(true);
        thread.start();
        TimeUnit.SECONDS.sleep(2);
        System.out.println("main thread end...");

    }

}
